from flask import abort
from flask import current_app
from flask import g
from flask import session

from info.commons import user_login_data
from info.models import News, User
from info.utils.response_code import RET
from . import news_blue
from flask import render_template, jsonify


#获取新闻详情
#请求路径
#请求方式 get
#请求参数 news_id
#返回响应
@news_blue.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):
    #根据新闻编号获取新闻
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="获取新闻失败")
    #判断新闻是否存在
    if not news:
        abort(404)

    #将热门新闻添加到首页
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(8).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取新闻失败 ")

    #将新闻对象添加到列表当中
    click_news_list = []
    for click_news in news_list:
        click_news_list.append(click_news.to_dict())

    # # 取出session中的用户编号
    # user_id = session.get("user_id")
    # # 获取用户对象
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)
    #返回响应
    data={
        "news":news.to_dict(),
        "click_news_list":click_news_list,
        "user_info": g.user.to_dict() if g.user else "",

    }
    return render_template("news/detail.html",data=data)